<?php

namespace App\Sidong\Controllers;

use App\Models\Notice;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class NoticeController extends AdminController
{
    protected $title = '公告管理';

    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->breadcrumb(['text' => '公告列表'])
            ->body($this->grid());
    }

    public function create(Content $content)
    {
        return $content
            ->title('新增公告')
            ->breadcrumb(['text' => '公告列表', 'url' => 'notices'], ['text' => '新增公告'])
            ->body($this->form());
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title('编辑公告')
            ->breadcrumb(['text' => '公告列表', 'url' => 'notices'], ['text' => '编辑公告'])
            ->body($this->form()->edit($id));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Notice);
        $admin = \Admin::user();
        $grid->model()->where('tenant_id', $admin->tenant_id)
        ->orderByDesc('sort');
        $grid->disableBatchActions();
        $grid->disableExport();
        $grid->actions(function ($actions) {
            // 去掉查看
            $actions->disableView();
        });
        $grid->column('id', 'ID');
        $grid->column('title', '标题');
        $grid->column('content', '内容')->limit(50)->modal('内容', function($modal) {
            return $this->content;
        });
        $states = [
            'on'  => ['value' => 1, 'text' => '启用', 'color' => 'success'],
            'off' => ['value' => 2, 'text' => '禁用', 'color' => 'danger'],
        ];
        $grid->column('is_enable', '启用状态')->switch($states);
        $grid->column('sort', '排序')->help('数值越大越靠前');
        $grid->column('created_at', '创建时间');
        return $grid;
    }

    protected function form()
    {
        $admin = \Admin::user();
        $form = new Form(new Notice);
        $form->hidden('tenant_id')->default($admin->tenant_id);
        $form->text('title', '标题')->placeholder('请输入标题，用于标识区分通知');
        $form->text('content', '通知内容')
            ->placeholder('请输入通知内容')
            ->help('用户在小程序页面展示的通知内容');
        $states = [
            'on'  => ['value' => 1, 'text' => '启用', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '禁用', 'color' => 'danger'],
        ];
        $form->switch('is_enable', '是否启用')
            ->default(1)
            ->help('注意：如果选择禁用则不会展示通知')
            ->states($states);
        $form->number('sort', '排序')
            ->default(1)
            ->min(1)
            ->help('输入排序数字，值越大越靠前');
        return $form;
    }
}
